package com.superfish.cutieshop.activities;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.superfish.cutieshop.BaseActivity;
import com.superfish.cutieshop.BaseApp;
import com.superfish.cutieshop.BaseConfig;
import com.superfish.cutieshop.R;
import com.superfish.cutieshop.been.BarrageBeen;
import com.superfish.cutieshop.been.ShareContent;
import com.superfish.cutieshop.been.User;
import com.superfish.cutieshop.dialog.AppLoading;
import com.superfish.cutieshop.dialog.SendDialog;
import com.superfish.cutieshop.parser.GsonAddBarrage;
import com.superfish.cutieshop.http.HttpError;
import com.superfish.cutieshop.http.HttpStores;
import com.superfish.cutieshop.http.ZokeParams;
import com.superfish.cutieshop.parser.GsonBarrage;
import com.superfish.cutieshop.utils.CommonUtil;
import com.superfish.cutieshop.utils.CutieToast;
import com.superfish.cutieshop.utils.DensityUtils;
import com.superfish.cutieshop.utils.HttpParams;
import com.superfish.cutieshop.utils.ImageConfig;
import com.superfish.cutieshop.utils.LogTest;
import com.superfish.cutieshop.utils.MD5Utils;
import com.superfish.cutieshop.utils.PersistTool;
import com.superfish.cutieshop.utils.ShareUtils;
import com.superfish.cutieshop.utils.TaobaoUtils;
import com.superfish.cutieshop.utils.UserInfo;
import com.superfish.cutieshop.view.BarrageView;

import org.apache.http.NameValuePair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

@ContentView(R.layout.activity_content_details)
public class ContentDetailsActivity extends BaseActivity {


    private int page;//弹幕的分页
    private int tid;
    private String url;
    private AppLoading appLoading;


    private String title;
    private String shareUrl;
    private ShareContent shareContent;

    public static void open(Activity act, String url, int tid, String title, String shareUrl) {
        Intent i = new Intent(act, ContentDetailsActivity.class);
        i.putExtra("tid", tid);
        i.putExtra("url", url);
        i.putExtra("title", title);
        i.putExtra("shareUrl", shareUrl);
        act.startActivity(i);
    }

    @ViewInject(R.id.content)
    private View mContent;


    @ViewInject(R.id.webView)
    private WebView mWebView;
    @ViewInject(R.id.barrageContainer)
    private RelativeLayout mBarrageContainer;

    private int mBarrageHeight = 0;
    private int mCount = 0;

    private boolean isFailed;//如果这个失败了 则弹幕也不开启

    private HashMap<Integer, Boolean> sendPosition = new HashMap<Integer, Boolean>();

    private List<BarrageBeen> mCmts = new ArrayList<>();//弹幕列表

    private int position;//取的位置
    //初始化的时候也要进行判断处理
    private boolean isOff;//是否关闭了

    private User mUser;

    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            //执行发布弹幕的逻辑
            mHandler.sendEmptyMessage(10);
        }
    };

    @Override
    protected void handleMsg(Message msg) {
        super.handleMsg(msg);
        switch (msg.what) {
            case 10:
                if (!isOff) {
                    if (mCmts.size() != 0) {
                        if (position >= mCmts.size()) {
                            position = 0;
                            return;
                        }
                        BarrageBeen barrageBeen = mCmts.get(position);
                        sendBarrage(barrageBeen);
                        position++;
                    }
                }
                break;
        }

    }

    private Timer mTimer = new Timer();

    //测试连接

    private Paint mPaint;
    private PlatformActionListener platformActionListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUser = UserInfo.getInstense(ContentDetailsActivity.this).getUser();
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");
        shareUrl = getIntent().getStringExtra("shareUrl");
        //测试
//        url = "http://moeadmin1.yuchats.com/index_Android.html";
        tid = getIntent().getIntExtra("tid", 0);
        intiWebSettings();
        initShareCallBack();
        mWebView.loadUrl(url);
        initListener();
        initBarrage();
        fetchBarrages(page);
        appLoading = new AppLoading(this);
        appLoading.setTips(R.string.apploading_loading);
        shareContent = new ShareContent(tid);
        shareContent.setTitle(title);
        shareContent.setImgUrl(BaseConfig.SHARE_IMAGE);
        shareContent.setUrl(shareUrl);
        shareContent.setSite(BaseConfig.SHARE_SITE);
        shareContent.setText(BaseConfig.SHARE_CONTRIBUTION_TEXT);
    }

    private void startTimer() {
        mTimer.schedule(timerTask, 100, 800);
    }

    private void stopTimer() {
        mTimer.cancel();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    private void initShareCallBack() {
        platformActionListener = new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                ((Activity) ContentDetailsActivity.this).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        CutieToast.show(context, "onComplete");
                        appLoading.dismiss();
                    }
                });
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                ((Activity) ContentDetailsActivity.this).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        CutieToast.show(context, "onError");
                        appLoading.dismiss();
                    }
                });
            }

            @Override
            public void onCancel(Platform platform, int i) {
                ((Activity) ContentDetailsActivity.this).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        CutieToast.show(context, "onCancel");
                        appLoading.dismiss();
                    }
                });
            }
        };
    }


    /**
     * 初始化设置弹幕
     **/
    private void initBarrage() {
        mBarrageHeight = (int) (DensityUtils.sp2px(this, 20) * 1.5);
        ViewGroup.LayoutParams layoutParams = mBarrageContainer.getLayoutParams();
        layoutParams.width = DensityUtils.sp2px(this, 20) * 100;
        mBarrageContainer.setLayoutParams(layoutParams);
        TextView textView = new TextView(this);
        textView.setTextSize(15);
        mPaint = textView.getPaint();
        mCount = (DensityUtils.getScreenH(ContentDetailsActivity.this) * 3 / 4) / mBarrageHeight;
        for (int i = 0; i < mCount; i++) {
            sendPosition.put(i, false);
        }
    }


    /**
     * 设置WebSettings
     **/
    private void intiWebSettings() {
        if (android.os.Build.VERSION.SDK_INT > 8) {// 判断sdk版本，使用不用的api消除fedingedge
            mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        } else {
            mWebView.setFadingEdgeLength(0);
        }
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setSupportZoom(false);
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setDatabasePath(BaseApp.getTempCache(this));
        webSettings.setAppCachePath(BaseApp.getTempCache(this));
        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);// 设置缓冲大小，8M
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(false);
        mWebView.setDownloadListener(new DownloadListener() {//  使用自带的浏览器下载文件
            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
    }

    /**
     * 设置WebView的一些监听
     **/
    private void initListener() {

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (isFailed) {
                    showNetFail();
                    return;
                }
                showContent();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showLoading();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode,
                                        String description, String failingUrl) {
                LogTest.wlj("onReceivedError=" + errorCode);
                isFailed = true;
                switch (errorCode) {
                    case WebViewClient.ERROR_TIMEOUT:
                    case WebViewClient.ERROR_CONNECT:
                    case WebViewClient.ERROR_HOST_LOOKUP:
                        // 没网
                        showNetFail();
                        break;
                    default:
                        // 没数据
                        break;
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogTest.wlj("url=" + url);
//                  拦截Url 进行判断 处理业务逻辑
//                mWebView.loadUrl(url);
                if (url.contains("openId=")) {
                    //买买买
                    String[] buys = url.split("openId=");

                    if (buys != null && buys.length != 0) {
                        String by = buys[1];
                        LogTest.wlj("by=" + by);
                        String[] bys = by.split("&from=");
                        if (bys != null && bys.length != 0) {
                            LogTest.wlj("id = " + bys[0] + "类型=" + bys[1]);
                            buy(bys[0], "tmall".equals(bys[1]) ? TaobaoUtils.TIANMAO : TaobaoUtils.TAOBAO);
                        }
                    }
                    return true;
                }

                if (url.contains("shareType=")) {
                    //分享
                    String[] shares = url.split("shareType=");
                    LogTest.wlj("" + shares[1]);
                    if (shares != null && shares.length != 0) {
                        share(shares[1]);
                    }
                    return true;
                }

                if (url.contains("tid=")) {
                    String[] tids = url.split("tid=");
                    if (tids != null && tids.length != 0) {
                        int tid = Integer.parseInt(tids[1]);
                        finish();
                        ContentDetailForNotifyActivity.open(ContentDetailsActivity.this, tid);
                    }
                    return true;
                }

                //本页面加载Url
                mWebView.loadUrl(url);
                return true;
            }

        });

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }
        });
    }


    /**
     * 发送弹幕
     **/
    private void sendBarrage(BarrageBeen b) {
        final BarrageView bar = new BarrageView(this, DensityUtils.getScreenW(ContentDetailsActivity.this), (int) -mPaint.measureText(b.contents));
        bar.mContentTv.setText(b.contents);
        ImageLoader.getInstance().displayImage(b.avatar, bar.mHead, ImageConfig.getCirclHeadOptions());

        if (mUser.uid == b.uid) {
            //我发送的
            bar.mContainer.setBackgroundResource(R.drawable.barrage_bg_me);
        } else {
            //别人发送的
            bar.mContainer.setBackgroundResource(R.drawable.barrage_bg);
        }
        bar.setOnAnimationEndListener(new BarrageView.OnAnimationEndListener() {
            @Override
            public void clearPosition() {
                sendPosition.put(bar.getPosition(), false);
            }

            @Override
            public void animationEnd() {
                mBarrageContainer.removeView(bar);
            }

        });

        for (int i = 0; i < mCount; i++) {
            if (sendPosition.get(i) == false) {
                bar.setPosition(i);
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT, mBarrageHeight);
                lp.addRule(RelativeLayout.ALIGN_PARENT_TOP);
                lp.topMargin = i * mBarrageHeight;
                mBarrageContainer.addView(bar, lp);
                bar.send();
                sendPosition.put(i, true);
                break;
            }
        }
    }


    //
    public String createKey(ZokeParams out) {
        String url = out.getUrl();
        List<NameValuePair> list = out.getQueryStringParams();
        if (list != null && list.size() != 0) {
            for (NameValuePair p : list) {
                url = url + "?" + p.getName() + "=" + p.getValue();
            }
        }
        url = MD5Utils.toMD5(url);
        return url;
    }


    @Override
    protected void onPause() {
        super.onPause();
        LogTest.wlj("onPause");
        isOff = true;
    }


    @Override
    public void onSuccess(ZokeParams out) {
        super.onSuccess(out);
        ResponseInfo info = (ResponseInfo) out.getResult();
        String result = (String) info.result;
        LogTest.wlj("" + result);
        String url = out.getUrl();
        if (url.equals(BaseConfig.UrlBank.barrages)) {
            //获取弹幕列表
            GsonBarrage gb = new GsonBarrage().fromJson(result);
            if (gb.info == null || gb.error_code != 0) {
                if (gb.error_code == 3001) {
                    // -- 被拉黑了 导致发不出去
                    CutieToast.show(getApplicationContext(), R.string.send_dont);
                }
                return;
            }

            if (gb.info.list == null || gb.info.list.length == 0) {
                return;
            }
            //缓存  再请求失败以后加载使用 防止弹幕出错
            String key = createKey(out);
            PersistTool.saveString(key, result);
            for (BarrageBeen b : gb.info.list) {
                mCmts.add(b);
            }
            startTimer();
            return;
        }

        if (url.equals(BaseConfig.UrlBank.addBarrage)) {
            //发布成功
            GsonAddBarrage gab = new GsonAddBarrage().fromJson(result);
            if (gab.info == null || gab.error_code != 0) {
                //发布失败哦
                CutieToast.show(getApplicationContext(), R.string.send_fail);
                return;
            }
            BarrageBeen barrageBeen = gab.info;
            mCmts.add(barrageBeen);
            sendBarrage(barrageBeen);
            //发布成功
            CutieToast.show(getApplicationContext(), R.string.send_ok);
            return;
        }
    }


    /**
     * 统计分享接口
     *
     * @param shareType 朋友圈1，微信好友2，QQ空间3，QQ好友4，新浪微博5
     */
    private void fetchAnalysShare(int shareType) {
        ZokeParams params = HttpParams.analysShare(mHashCode, tid, shareType);
        HttpStores.getInstense().post(params);
    }

    @Override
    public void onFails(ZokeParams out) {
        super.onFails(out);
        HttpError e = (HttpError) out.getResult();
        LogTest.wlj("错误=" + e.exception.getExceptionCode());
        String url = out.getUrl();
        //发布失败哦
        if (url.equals(BaseConfig.UrlBank.addBarrage)) {
            CutieToast.show(getApplicationContext(), R.string.send_fail);
            return;
        }

        if (url.equals(BaseConfig.UrlBank.barrages)) {
            String key = createKey(out);
            String json = PersistTool.getString(key, "");
            if (!TextUtils.isEmpty(json)) {
                //获取弹幕列表
                GsonBarrage gb = new GsonBarrage().fromJson(json);
                if (gb.info == null || gb.error_code != 0) {
                    return;
                }

                if (gb.info.list == null || gb.info.list.length == 0) {
                    return;
                }
                for (BarrageBeen b : gb.info.list) {
                    mCmts.add(b);
                }
                startTimer();
            }
            return;
        }

    }

    /**
     * 获取弹幕列表
     **/
    private void fetchBarrages(int p) {
        ZokeParams params = HttpParams.getBarrages(mHashCode, p, tid);
        HttpStores.getInstense().get(params);
    }

    /**
     * 添加弹幕
     **/
    private void addBarrage(int phrashId, String text) {
        ZokeParams params = HttpParams.addBarrage(mHashCode, tid, phrashId, text);
        HttpStores.getInstense().post(params);
    }


    @OnClick(R.id.title_back)
    public void onClickTitleBack(View v) {
        finish();
    }

    @ViewInject(R.id.messageTv)
    private TextView mMsgOn;

    @OnClick(R.id.msg_on)
    public void onClickOn(View v) {
        //弹幕开关
        isOff = !isOff;
        mMsgOn.setSelected(!mMsgOn.isSelected());
        mBarrageContainer.setVisibility(mMsgOn.isSelected() ? View.INVISIBLE : View.VISIBLE);
    }

//    @OnClick(R.id.comment)
//    public void onClickComment(View v) {
//        SendDialog mSendDialog = new SendDialog(ContentDetailsActivity.this, ContentDetailsActivity.this);
//        mSendDialog.show();
//    }


    public void showLoading() {
        isOff = true;
        mPageState.showLoading();
        mContent.setVisibility(View.GONE);
        mPageState.setOnReloadListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFailed = false;
                showLoading();
                mWebView.loadUrl(url);
            }
        });
    }

    public void showNetFail() {
        isOff = true;
        mPageState.showNetFailed();
        mContent.setVisibility(View.GONE);
    }

    public void showContent() {
        isOff = false;
        mPageState.hide();
        mContent.setVisibility(View.VISIBLE);
    }


    /**
     * 跳转淘宝购买
     **/
    public void buy(String openId, int type) {
        if (!CommonUtil.getNetWorkStates(ContentDetailsActivity.this)) {
            CutieToast.showNetFailed(getApplicationContext());
            return;
        }
        LogTest.wlj("类型=" + type);
        TaobaoUtils.showTaokeItemDetail(this, type, openId);
    }

    public void share(String type) {
        if (!CommonUtil.getNetWorkStates(ContentDetailsActivity.this)) {
            CutieToast.showNetFailed(getApplicationContext());
            return;
        }
        if (type.equals("sina")) {
            //新浪
            appLoading.show();
//            ShareUtils.shareToWeibo(shareContent, platformActionListener);
            ShareUtils.startShareToWeibo(this, shareContent, platformActionListener, appLoading);
            fetchAnalysShare(5);
            return;
        }
        if (type.equals("qq")) {
            //qq
            appLoading.show();
            ShareUtils.shareToQQ(shareContent, platformActionListener);
            fetchAnalysShare(4);
            return;
        }
        if (type.equals("wechat")) {
            //微信
            if (CommonUtil.isApkExist(this, "com.tencent.mm")) {
                appLoading.show();
                ShareUtils.shareToWechat(shareContent, platformActionListener);
                fetchAnalysShare(2);
            } else {
                CutieToast.show(this, R.string.share_nowechatapp);
            }
            return;
        }
        if (type.equals("space")) {
            //QQ空间
            appLoading.show();
            ShareUtils.shareToQZone(shareContent, platformActionListener);
            fetchAnalysShare(3);
            return;
        }
        if (type.equals("pyq")) {
            //朋友圈
            if (CommonUtil.isApkExist(this, "com.tencent.mm")) {
                appLoading.show();
                ShareUtils.shareToWechatMoments(shareContent, platformActionListener);
                fetchAnalysShare(1);
            } else {
                CutieToast.show(this, R.string.share_nowechatapp);
            }
            return;
        }
    }


//    @Override
//    public void send(String text) {
//        addBarrage(0, text);
//    }
//
//    @Override
//    public void sendPhase(int id, String text) {
//        addBarrage(id, text);
//    }

    @Override
    protected void onResume() {
        super.onResume();
        isOff = false;
        appLoading.dismiss();
    }
}
